// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// U [author] rhyme_lph
// u [email]  rhymelph@gmail.com
// v [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/company_entity.dart';
import 'package:finance_app/src/entities/current_subscription_entity.dart';
import 'package:finance_app/src/entities/setting_app_entity.dart';
import 'package:finance_app/src/http_service/http_coa_service.dart';
import 'package:finance_app/src/http_service/http_company_service.dart';
import 'package:finance_app/src/http_service/http_subscription_service.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/date_time_select_bottom_sheet.dart';
import 'package:flutter/material.dart';

class CreateBusinessProfileProvider extends BaseProvider {
  TextEditingController businessNameController = TextEditingController();
  FocusNode businessNameFocusNode = FocusNode();

  List<String> businessTypes = <String>[];

  SettingAppBusinessType currentSelectBusinessType;
  SettingAppIndustryType currentSelectIndustryType;
  DateTime startDate;
  DateTime endDate;

  bool enable = false;

  bool passwordError = false;

  bool showNext = false;
  bool enableAuth = false;
  int step = 0;

  void onNext() {
    businessNameFocusNode.unfocus();
    showNext = true;
    update();
  }

  @override
  void dispose() {
    super.dispose();
    businessNameController.dispose();
    businessNameFocusNode.dispose();
  }

  @override
  void initState() {
    super.initState();
    DateTime time = DateTime.now();
    startDate = DateTime(time.year, 1, 1);
    endDate = DateTime(time.year, 12, 31);
    businessTypes = Config.settingApp.businessType.map((e) => e.name).toList();
    businessNameController.addListener(_handleUpdateBusiness);
  }

  void _handleUpdateBusiness() {
    if (businessNameController.text.length > 0 &&
        currentSelectBusinessType != null) {
      if (enable == false) {
        enable = true;
        update();
      }
    } else {
      if (enable == true) {
        enable = false;
        update();
      }
    }
  }

  @override
  Future get dataFuture => null;

  void onChangeBusinessType(String item1) {
    if (currentSelectBusinessType?.name != item1)
      currentSelectBusinessType = Config.settingApp.businessType
          .firstWhere((element) => element.name == item1, orElse: () => null);
    update();
    _handleUpdateBusiness();
  }

  void onStartExploring() async {
    final name = businessNameController.text;

    bool isSuccess = false;
    await post(
        HttpCompanyService.createCompanies(
            name, currentSelectBusinessType.key, currentSelectIndustryType.key),
        loadingTip: S.current.loading,
        autoHandler: AutoHandler.Toast, onSuccess: (result) async {
      isSuccess = true;
      CompanyEntity companyEntity = getEntityFromResult<CompanyEntity>(result);
      Config.userProfile.defaultCompanyId = companyEntity.id.toString();
      await post(
          HttpCompanyService.updateCompanies(
            companyEntity.id,
            financial_year_start_at:
                DateTimeUtils.formatDateTime(startDate, 'yyyy-MM-dd'),
            financial_year_end_at:
                DateTimeUtils.formatDateTime(endDate, 'yyyy-MM-dd'),
            financial_year_period: 12,
          ),
          autoHandler: AutoHandler.Toast,
          loadingTip: S.current.loading, onSuccess: (result) {
        companyEntity = getEntityFromResult<CompanyEntity>(result);
      });

      await RProvider.myProvider.updateGlobalMap();

      await HttpCoaService.coaList();

      await post(HttpSubscriptionService.getCompaniesSubscription(),
          onSuccess: (result) async {
        CurrentSubscriptionEntity entity =
            getEntityFromResult<CurrentSubscriptionEntity>(result);
        RProvider.myProvider.globalMap[ConfigKey.currentSubscription] = entity;
        await RProvider.myProvider.updateGlobalMap();
      });
    });

    if (isSuccess == true)
      Routes.navigateTo(RouterGenProviders.dashboardPage, clearStack: true);
  }

  void onSelectIndustryType(String value) {
    if (currentSelectIndustryType?.name != value) {
      currentSelectIndustryType = Config.settingApp.industryType
          .firstWhere((element) => element.name == value, orElse: () => null);
      update();
    }
  }

  void onChangeStartDate() {
    obtainContext?.call((context) async {
      DateTime result = await showDateTimeSelectBottomSheet(
          context, S.current.financial_year_start_date, startDate,
          withinFinancialYear: false);
      if (result != null) {
        startDate = result;
        update();
      }
    });
  }

  void onChangeEndDate() {
    obtainContext?.call((context) async {
      DateTime result = await showDateTimeSelectBottomSheet(
          context, S.current.financial_year_end_date, endDate,
          withinFinancialYear: false);
      if (result != null) {
        endDate = result;
        update();
      }
    });
  }
}
